package com.wewins.fota.controller;

import com.alibaba.fastjson.JSON;
import com.wewins.fota.bean.bo.SysLog;
import com.wewins.fota.bean.dto.ResponseRst;
import com.wewins.fota.common.constant.HttpConst;
import com.wewins.fota.common.util.FileUtil;
import com.wewins.fota.service.SysLogService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.List;

import static org.apache.tools.ant.launch.Locator.encodeURI;

@Slf4j
@Controller
@RequestMapping("/syslog")
public class SysLogController {
    private final SysLogService sysLogService;

    public SysLogController(SysLogService sysLogService) {
        this.sysLogService = sysLogService;
    }

    @GetMapping("/query")
    @ResponseBody
    public ResponseRst<List<SysLog>> queryAll() {
        return ResponseRst.<List<SysLog>>builder()
                .data(sysLogService.queryAll())
                .build().withOk();
    }


    @GetMapping("/download/{fileName:.*}")
    public void download(HttpServletResponse response, @PathVariable String fileName) throws IOException {
        File file = sysLogService.download(fileName);
        if (file != null) {
            response.setStatus(HttpStatus.OK.value());
            response.setCharacterEncoding("utf-8");
            response.setContentType("application/octet-stream");
            String uriName = encodeURI(fileName);
            response.setHeader("Content-Disposition", "attachment;filename=\"" + uriName + "\";filename*=utf-8''" + uriName);
            FileUtil.load(response, file);
        } else {
            log.error("file not exist: " + fileName);
            response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
            JSON.writeJSONString(response.getWriter(), ResponseRst.builder().build().withDefaultError(HttpConst.MSG_FAIL_FILE_NOT_EXIST));
        }
    }
}
